package com.laicunba.ext.web.controller.console.sys;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.laicunba.ext.web.controller.BaseController;
import com.laicunba.pojo.AccountDO;
import com.laicunba.service.AccountBalanceSheetService;
import com.laicunba.service.AccountService;
import com.laicunba.service.exception.MyException;
import com.laicunba.util.StringUtil;

@Controller
@RequestMapping(value = "/console/ext/sys")
public class AccountBalanceController extends BaseController {

	@Autowired
	private AccountBalanceSheetService accountBalanceSheetService;
	@Autowired
	private AccountService accountService;

	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/doImproveBalance.htm")
	public String doImproveBalance(String balanceString, String remark) {
		JSONObject json = new JSONObject();
		try { 
			if (StringUtil.isEmpty(remark)) {

				json.put("code", "REMARK_CANT_EMPTY");
				return json.toJSONString();
			}
			Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
			for (String str : balanceString.split(",")) {
				String[] item = str.split(":");
				map.put(item[0].toUpperCase().trim(), BigDecimal.valueOf(Double.parseDouble(item[1])));
			}
			for (String id : map.keySet()) {
				if (accountService.get(AccountDO.class, id) == null) {
					json.put("code", "SUBJECT_NOT_FOUND");
					return json.toJSONString();
				}
			}
			accountBalanceSheetService.accountingImprove(map, remark);
			json.put("code", "SUCCESS");
		} catch (MyException e) {
			json.put("code", e.getCode());
			return json.toJSONString();
		} catch (Exception e) {
			json.put("code", "error");
			return json.toJSONString();
		}
		return json.toJSONString();
	}

}
